#!/usr/bin/python
#coding:utf-8

urls=['https://shimo.im/spreadsheet/E4VOSRksta0rA4K8','https://shimo.im/doc/MMFtF5S3DMEpo3MO','https://shimo.im/doc/K0H3PEk4srkRl8Mr']
urls=['https://shimo.im/spreadsheet/E4VOSRksta0rA4K8']

import os,requests,json,re,sys

stdi,stdo,stde=sys.stdin,sys.stdout,sys.stderr
reload(sys)
sys.setdefaultencoding('utf-8')
file_list=[];
headers={'content-type': 'application/json','Content-Type':'application/json; charset=UTF-8','User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36','X-Requested-With':'XMLHttpRequest'}
def downloadfile(url):
    if not url:
        print '请正确传入url'
        exit()
    global headers
    doc=requests.get(url,headers=headers,verify=False)
    doc=doc.content
    doc=re.findall('<title>(.*)<\/title>',doc)[0]
    title=doc.decode('utf-8')
    print '正在下载【'+title+'】...'
    #请求得到token值

    first_url='https://shimo.im/export?title='+title+'&type=docx&guid=K0H3PEk4srkRl8Mr'
    #url='https://shimo.im/doc/K0H3PEk4srkRl8Mr'
    url_ext=url.split('/')
    url_ext=url_ext[-1]
    first_url='https://shimo.im/export?title='+title+'&type=docx&guid='+url_ext
    #请求真正的文件
    r=requests.get(first_url,headers=headers,verify=False)
    print r.content
    tt=json.loads(r.content)
    print tt
    exit()
    filename=tt['data']['filename']
    second_url='https://shimo.im/download/export?filename='+filename+'&downloadAs='+title+'.docx'
    r=requests.get(second_url,headers=headers,verify=False)

    #如果些文件真在则删除重新生成
    if os.path.isfile(os.getcwd()+'/'+title+'.docx'):
        os.remove(os.getcwd()+'/'+title+'.docx')
    with open(title+".docx", "w") as code:
        code.write(r.content)
        code.close()
    global file_list
    file_list.append(title+'.docx')
    print '【'+title+'】下载完毕'

#url=input('请输入文档链接')
print '开始下载文件...'
print '---------------------------------'
#请求标题
for index,url in enumerate(urls):
    downloadfile(url)
print '---------------------------------'
print '文件全部下载完成'